var buttonList=[];
var addFlag=true;
var updateFlag=true;
var roleInfo = {
    
    init : function() {
        //初始化按钮
        setMenuButtonOpermission();
        
        roleInfo.evenBind();
        roleInfo.getRoleButtonList();
        roleInfo.loadData();
        var datas=roleInfo.getDeptOrgData();
        roleInfo.initCombotree($("#addDeptId"),datas);
        roleInfo.initCombotree($("#editDeptId"),datas);
        systemType = getUrlParam("systemType");
    },
    evenBind : function() {
        // ----------------------------------------------------------------------->
        // 添加角色
        // ----------------------------------------------------------------------->
        $('#add').bind('click', function() {
            $('#createRoleDiv').window('open');
            $('#createRoleForm').form('clear');
        });

        // 取消
        $('#cancelCreateRole').bind('click', function() {
            $('#createRoleForm').form('clear');
            $('#createRoleDiv').dialog('close');
        });

        // 提交
        $('#submitCreateRole').bind('click', function() {
        	if(addFlag){
        		addFlag=false;
        		$('#createRoleForm').form('submit', {
                    url : getProjectUrl('/bfs/role/add'),
                    onSubmit : function() {
                    	addFlag=true;
                        var _flag = $(this).form('validate');
                        if (!_flag) {
                            return false;
                        }
                        var addRoleName = $('#addRoleName').val();
                        var _valid = roleInfo.validRoleName(null, addRoleName);
                        if (!_valid) {
                            $.messager.alert('提示', '角色名称已存在或为空!', 'warning');
                            return false;
                        }
                        addFlag=false;
                        return true;
                    },
                    success : function(data) {
                        $.resultHandler(data, function() {
                            $('#createRoleForm').form('clear');
                            $('#createRoleDiv').dialog('close');
                        });
                        
                        $("#searchRoleName").textbox('setText','');
                        $("#searchRoleName").textbox('setValue','');
                        roleInfo.loadData();
                        addFlag=true;
                    }
                });
        	}
            
        });
        // -----------------------------------------------------------------------<

        // ----------------------------------------------------------------------->
        // 批量删除角色
        // ----------------------------------------------------------------------->
        $('#deletes').bind('click', function() {
            var checkRecord = $('#listDataEx1').datagrid('getChecked');
            if (!checkRecord || checkRecord.length === 0) {
                $.messager.alert('提示', '请先选中记录!', 'warning');
                return;
            }
            var _msg = '您确定要删除选中的' + checkRecord.length + '条记录吗?<br/>注意：<font color="red">删除可能会造成系统异常</font>';
            $.messager.confirm('提示', _msg, function(r) {
                if (r) {
                    var roleIds = [];
                    for (var i = 0; i < checkRecord.length; i++) {
                        roleIds[i] = checkRecord[i].roleId;
                    }
                    ajaxProcess({
                        url : getProjectUrl("/bfs/role/drop"),
                        data :{
                            roleIds : roleIds
                        },
                        traditional : true,
                        async:true,
                        successHandle : function(data) {
                            $('#listDataEx1').datagrid('reload');
                        }
                    });
                }
            });
        });

        // ----------------------------------------------------------------------->
        // 刷新表单操作
        // ----------------------------------------------------------------------->
        $('#refreshRole').on('click', function() {
            $('#searchRoleName').val('');
            roleInfo.loadData();
        });

        // 修改角色取消
        $('#cancelEditRole').bind('click', function() {
            $('#editRoleForm').form('clear');
            $('#editRoleDiv').dialog('close');
        });

        // 修改角色提交
        $('#submitEditRole').bind('click', function() {
        	if(updateFlag){
        		updateFlag=false;
        		$('#editRoleForm').form('submit', {
                    url : getProjectUrl('/bfs/role/edit'),
                    onSubmit : function() {
                    	updateFlag=true;
                        var _flag = $(this).form('validate');
                        if (!_flag) {
                            return false;
                        }
                        var editRoleName = $('#editRoleName').val();
                        var editRoleId = $('#editRoleId').val();
                        var _valid = roleInfo.validRoleName(editRoleId, editRoleName);
                        if (!_valid) {
                            $.messager.alert('提示', '角色名称已存在或为空!', 'warning');
                            return false;
                        }
                        updateFlag=false;
                        return true;
                    },
                    success : function(data) {
                        $.resultHandler(data, function() {
                            $('#editRoleForm').form('clear');
                            $('#editRoleDiv').dialog('close');
                        });
                        $('#listDataEx1').datagrid('reload');
                        updateFlag=true;
                    }
                });
        	}
            
        });
    },
    getRoleButtonList:function(){
    	 
    	  ajaxProcess({
              url : getProjectUrl("/bfs/configuration/rolebuttonlist"),
              data :{
              },
              requestType : 'POST',
              traditional : true,
              async:false,
              successHandle : function(data) {
                  buttonList= data;
                 
              }
          });
    	 
    },
    //获取部门组织树
    getDeptOrgData:function(){
        var result=[];
        
        ajaxProcess({
            url:getProjectUrl('/bfs/dept/combobox'),
            requestType : 'POST',
            async:false,
            successHandle : function(data) {
                for(var i=0;i<data.rows.length;i++){
                    result.push(data.rows[i]);
                }
            }
        });
        
        return result;
        
    },
    //初始化树下拉框
    initCombotree:function(DOM,data){
        
        DOM.combotree({
            data:data
        })
        
    },
    // ----------------------------------------------------------------------->
    // 修改角色
    // ----------------------------------------------------------------------->
    openEditRoleDiv : function(id, name, description,deptId) {
        if(deptId === "null"){
            deptId="";   
        }
        $('#editRoleDiv').window({
            onOpen : function() {
                $('#editRoleForm').form('load', {
                    roleId : id,
                    roleName : name,
                    description : description,
                    deptId:deptId
                });
            }
        });
        $('#editRoleDiv').window('open');
    },

    // ----------------------------------------------------------------------->
    // 删除角色
    // ----------------------------------------------------------------------->
    openRemoveRoleDiv : function(id) {
        var _msg = '您确定要删除该条记录吗?<br/>注意：<font color="red">删除可能会造成系统异常</font>';
        $.messager.confirm('提示', _msg, function(r) {
            if (r) {
                ajaxProcess({
                    url:getProjectUrl("/bfs/role/drop"),
                    requestType : 'POST',
                    data:{
                        roleIds:id
                    },
                    async:true,
                    traditional:true,
                    successHandle : function(data) {
                        $('#listDataEx1').datagrid('reload');
                    }
                });
            }
        });
    },

    // 验证角色名称
    validRoleName : function(_roleId, _roleName) {
        var _flag;
        ajaxProcess({
            url:getProjectUrl("/bfs/role/valid"),
            requestType : 'POST',
            data:{
                roleId : _roleId,
                roleName : _roleName
            },
            async:false,
            traditional:true,
            successHandle : function(data) {
                _flag = data.result;
            }
        });
        
        
        return _flag;
    },
    refreshData : function() {
        roleInfo.loadData();
    },
    beforeLoad : function() {
        $('#createRoleDiv').dialog('destroy', true);
        $('#editRoleDiv').dialog('destroy', true);
    },
    // ----------------------------------------------------------------------->
    // 打开设置角色菜单的窗口
    // ----------------------------------------------------------------------->
    openSetMenuDiv : function(_roleId) {
    	var url=getProjectUrl("/views/bfs/editRoleMenu.html");
    	roleInfo.openDiv("rolemenu"+_roleId,"设置角色菜单",url,_roleId+"&systemType="+systemType,860,488);
    	//roleInfo.openDiv("rolemenu"+_roleId,"设置角色菜单",url,_roleId);
    },

    // ----------------------------------------------------------------------->
    // 打开设置分配用户的窗口
    // ----------------------------------------------------------------------->
    openAssignUserRolesDiv : function(_roleId) {
    	var url=getProjectUrl("/views/bfs/assignUserRoles.html");
    	roleInfo.openDiv("userrole"+_roleId,"分配用户",url,_roleId,500,488);
    },
    loadData : function() {
    	$(".list").show();
		$(".nolist").hide();
        $('#listDataEx1').datagrid({
            url : getProjectUrl('/bfs/role/list'),
            queryParams : {
                searchRoleName : $.trim($("#searchRoleName").val())
            },
            columns : [ [ {
                field : 'ck',
                checkbox : true
            }, {
                field : 'roleId',
                title : 'ID',
                width : 100,
                hidden : true
            }, {
                field : 'roleName',
                title : '角色名称',
                width : 100
            }, {
                field : 'description',
                title : '角色描述',
                width : 100
            }, {
                field : 'createTime',
                title : '创建时间',
                width : 60
            }, {
                field : 'deptName', 
                title : '部门名称',
                width : 100
            }, {
            	field : "control",
                title : "操作",
                width : 140,
                formatter : function(value, row) {
                   var dynacontrol='';
                   var width=750;
                   var height=506;
                   for(var i=0;i<buttonList.length;i++)
                 		{
                       dynacontrol += '<a class="btn-stationrole" href="javascript:void(0)" name='+buttonList[i].buttonCode+' title='+buttonList[i].buttonName+' onclick="roleInfo.openDiv(\'button' + +row.roleId + '\',\'' + buttonList[i].buttonName + '\',\'' + buttonList[i].url + '\','+row.roleId+','+width+',\''+height+'\');"></a>';
                 		}
                    var control = '<span style="height: auto;">';
                    control += '<a class="btn-userrole" href="javascript:void(0)" name="assignUserRoles" title="分配用户" onclick="roleInfo.openAssignUserRolesDiv(\'' + row.roleId + '\');"></a>';
                    control += '<a class="btn-menurole" href="javascript:void(0)" name="setMenu" title="菜单权限" onclick="roleInfo.openSetMenuDiv(\'' + row.roleId + '\');"></a>';
                    control +=dynacontrol;
                    control += '<a class="btn-edit" href="javascript:void(0)" name="edit" title="编辑" onclick="roleInfo.openEditRoleDiv(\'' + row.roleId + '\',\'' + row.roleName + '\',\'' 
                    + row.description + '\',\''+row.deptId+'\');"></a>';                  
                    control += '<a class="btn-delete" href="javascript:void(0)" name="delete" title="删除" onclick="roleInfo.openRemoveRoleDiv(\'' + row.roleId + '\');"></a>';                 
                    control += '</span>';
                    return control;
                  }
            } ] ],
            rownumbers : true,
            method : 'POST',
            pagination : true,
            pageList : [ 20, 50, 100, 200 ],
            pageSize : 20,
            fitColumns : true,
            autoRowHeight : true,
            onLoadSuccess : function(data) {
                setMenuButtonOpermission();
                
                $('.menucls').linkbutton();
                if(data.rows === null || data.rows.length === 0){
					   $(".list").hide();
					   $(".nolist").css("height", $(".list").outerHeight()).show();	 
				}
            }
        });
    },
    openDiv : function(id,sName,url,roleId,width,heigth) {
		openDialogById(id, sName, url+"?roleId="+roleId, {}, width,heigth);
	}
};

$(function() {
    resetSize();
    roleInfo.init();
});

 
